//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { Image as VanImage } from "vant";
import { scrollMixin } from "utils/mixin";
export default {
  name:'',
  //import引入的组件需要注入到对象中才能使用
  components: { VanImage },
  mixins: [scrollMixin], //加载更多
  data() {
  return {
    query:{
      keyword:'',
      filter_ids:'',
      page:1,
      basic_info:1
    },
    tagList:[],
    tagIndex:[],
    goodsList:[],
    isLoadMore: true,
    totalPage: 0,
    timer: "", //防抖时间
    coThemeColor:'',
    productShow:false,
    tagHeight:0,
    productTitle:'产品中心',
    childArr:[],
  };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    goodsTo(item) {
      this.$router.push(this.fun.getUrl("goods", { id: item.id }));
    },
    debounce(fn, delay) {
      let last, deferTimer;
      return function(args) {
        let that = this;
        let _args = arguments;
        let now = +new Date();
        if (last && now < last + delay) {
          clearTimeout(deferTimer);
          deferTimer = setTimeout(function() {
            last = now;
            fn.apply(that, _args);
          }, delay);
        } else {
          last = now;
          fn.apply(that, _args);
        }
      };
    },
    colorFin(a) { //处理主题色
      a = a.substring(1);
      a = a.toLowerCase();
      let b = new Array();
      for (let x = 0; x < 3; x++) {
        b[0] = a.substr(x * 2, 2);
        b[3] = "0123456789abcdef";
        b[1] = b[0].substr(0, 1);
        b[2] = b[0].substr(1, 1);
        b[20 + x] = b[3].indexOf(b[1]) * 16 + b[3].indexOf(b[2]);
      }
      return b[20] + "," + b[21] + "," + b[22];
    },
    searchChange(val) {
      this.query.page = 1;
      this.query.keyword = val;
      if (this.timer) clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.debounce(this.getData());
      }, 500);
    },
    productBtn() {
      this.productShow = !this.productShow;
    },
    listChildBtn(index) {
      this.tagList[index].heightChecked = !this.tagList[index].heightChecked;
      this.tagHeight = 0;
      if(this.tagList.length > 4 && !this.tagHeight) { //处理超过4个标签显示还是隐藏
          this.$nextTick(() => { //遍历ref处理标签的高度
            if(this.$refs.tag && this.$refs.tag.length >0) {
              this.$refs.tag.map((item,index) => {
                if(index < 4) {
                  this.tagHeight += item.clientHeight -1
                }
              })
            }
          });
      } 
    },
    tagClick(data) {
      let {itemChild,index,indexChild} =data;
      let childArr = [];
      if(itemChild.id) { //其他标签是多选的
        this.tagList[index].value[indexChild].checked = !this.tagList[index].value[indexChild].checked;
        this.tagList[index].value[0].checked = false;
      } else {
        this.tagList[index].value.map((item,index) => { //如果选择全部的话，其他标签不选择
          item.checked = false;
        })
        this.tagList[index].value[0].checked = true;
      }
      this.tagList.map((item,index) => {
        item.value.map((childItem,childIndex) => {
          if(childItem.checked) {
            childArr.push(childItem.id);
          }
        })
      })
      let arrId = childArr.filter((item,index) =>  item != '' || item != 0);
      this.query.filter_ids = arrId.join(',');
      this.query.page = 1;
      this.getData();
    },
    initData() {
      this.tagHeight = 0;
      this.isLoadMore = true;
      this.productShow = false;
      this.query.keyword = '';
      this.query.filter_ids = '';
      this.query.page = 1;
      this.tagList = [];
      this.goodsList = [];
    },
    getTagData() {
      $http
        .get('goods.goods.get-tag-goods-list', '获取中')
        .then(response => {
          if (response.result == 1) {
            let basic_info = JSON.parse(localStorage.getItem("yz_basic_info"));
            let themeColor = basic_info.theme_color;
            this.coThemeColor = this.colorFin(themeColor ) || this.colorFin('#F15353');
            let data = response.data;
            if(data.title) {
              this.productTitle = data.title;
              this.fun.setWXTitle(data.title);
            }
            this.tagList = data.tag_list;
            
            if(this.tagList.length > 0) { //遍历标签处理数据
             
              this.tagList.map((item,index) => {
                this.$nextTick(() => {
                  item.value.map((childItem,childIndex) => {
                    this.$set(childItem, 'checked', false)
                    if(childIndex == 0) {
                      childItem.checked = true;
                    }
                    if(this.$refs.listChild) {
                      console.log(this.$refs.listChild[index].clientHeight);
                      this.$set(item, 'height', this.$refs.listChild[index].clientHeight)
                      this.$set(item, 'heightChecked',false)
                    }
                    if(this.$refs.tagItem) {
                       //获取渲染后元素的外边距,在390的手机屏不适配，其他都可以，只能写死适应375以上
                      // const styles = window.getComputedStyle(this.$refs.tagItem[0]);
                      // const marginBottom = parseFloat(styles.marginBottom) ;
                      // console.log(marginBottom);
                      this.$set(item, 'tagHeight', ((this.$refs.tagItem[0].clientHeight + 9) * 2))
                      console.log('333333333', ((this.$refs.tagItem[0].clientHeight + 9) * 2)); 
                    }
                    
                  })
                })
              })
            }
            console.log( this.tagList);
            if(this.tagList.length > 4 && !this.tagHeight) { //处理超过4个标签显示还是隐藏
              setTimeout(() => {
                this.$nextTick(() => { //遍历ref处理标签的高度
                  if(this.$refs.tag && this.$refs.tag.length >0) {
                    this.$refs.tag.map((item,index) => {
                      if(index < 4) {
                        this.tagHeight += item.clientHeight-1
                      }
                    })
                  }
                });
              },200)
            }
          } else {
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    //获取数据
    getData() {
      $http
        .get('goods.goods.search-tag-goods', this.query, '获取中')
        .then(response => {
          if (response.result == 1) {
            let data = response.data;
            this.goodsList = data.data || [];
            this.isLoadMore = true;
            this.totalPage = data.last_page;
            if (!this.totalPage) {
              this.query.page = 0;
            }
          } else {
            this.query.page = this.query.page - 1;
            this.isLoadMore = false;
            this.$toast(response.msg);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    //获取更多数据
    getMoreData() {
      this.isLoadMore = false; // 防止多次请求分页数据
      if (this.query.page >= this.totalPage) {
        return;
      } else {
        this.query.page = this.query.page + 1;
        $http.get("goods.goods.search-tag-goods", this.query, "加载中").then(
          res => {
            this.isLoadMore = true;
            if (res.result === 1) {
              let data = res.data;
              let list = data.data;
              this.goodsList = [...this.goodsList, ...list]; //数组拼接
            } else {
              this.page = this.page - 1;
              this.isLoadMore = false;
            }
          },
          function(response) {
            console.log("response", response);
            // error callback
          }
        );
      }
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
  
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
  
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {
    this.initData();
    this.getTagData();
    this.getData();
  }, //如果页面有keep-alive缓存功能，这个函数会触发
}